/**
 * @file unique_lock_defer.cpp
 * @author your name (you@domain.com)
 * @brief 演示unique lock defer的用法
 * @version 0.1
 * @date 2022-04-16
 * 
 * @copyright Copyright (c) 2022
 * 
 */

#include <iostream>
#include <mutex>
#include <thread>

std::mutex mtx_;

/**
 * unique_lock构造时可以不立即lock，而在需要的时候再去lock
 * 
 */

void f(void)
{
    std::unique_lock<std::mutex> lk(mtx_, std::defer_lock);

     if (lk.try_lock())
    {
        std::cout<< "lock ok" << std::endl;
    }
    else
    {
        std::cout<< "lock failed" << std::endl;
    }

    std::unique_lock<std::mutex> lk2(mtx_, std::defer_lock);

    if (lk2.try_lock())
    {
        std::cout<< "lock ok" << std::endl;
    }
    else
    {
        std::cout<< "lock failed" << std::endl;
    }

    std::cout<< "a ha a ha" << std::endl;
}

int main(void)
{
    std::thread t1(f);
    t1.join();
}